package com.breeze.lib

import android.app.Application
import android.content.pm.PackageManager
import android.content.res.AssetManager
import android.content.res.Resources
import java.util.*

class SkinManager : Observable {
    private var mContext: Application

    private constructor(application: Application) {
        this.mContext = application
        // 监听Activity生命周期，用于替换Factory2
        application.registerActivityLifecycleCallbacks(MyActivityLifeCycleCallbacks(this))
    }

    companion object {
        private var instance: SkinManager? = null
        val supportAttribute = arrayListOf<String>()

        init {
            supportAttribute.add("background");
            supportAttribute.add("src");
            supportAttribute.add("textColor");
        }

        fun init(application: Application) {
            if (instance == null) {
                instance = SkinManager(application)
            }
        }

        fun getInstance(): SkinManager {
            return instance!!
        }
    }

    fun applySkin(skinPath: String) {
        val appResources = mContext.resources
        // 加载皮肤资源
        val am = AssetManager::class.java.newInstance()
        val method =
            am.javaClass.getMethod("addAssetPath", String::class.java) // addAssetPath添加指定路径的资源
        method.invoke(am, skinPath)
        var skinResources =
            Resources(am, appResources.displayMetrics, appResources.configuration)
        // 获取皮肤包名
        val packageArchiveInfo =
            mContext.packageManager.getPackageArchiveInfo(skinPath, PackageManager.GET_ACTIVITIES)
        SkinResources.init(appResources, skinResources, packageArchiveInfo.packageName)
        // 通知观察者去设置皮肤
        setChanged()
        notifyObservers()
    }
}